<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" label-width="120px">
      <el-form-item label=" 服务功能名称 " prop="functionName">
        <el-input
          v-model="queryParams.functionName"
          placeholder="请输入 服务功能名称 "
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>

      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['ledger:function:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['ledger:function:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['ledger:function:remove']"
        >删除</el-button>
      </el-col>
    </el-row>

    <el-table v-loading="loading" :data="functionList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="功能名称" align="center" prop="functionName" />
      <el-table-column label="功能图标" align="center" prop="functionIcon">
        <template slot-scope="scope">
          <div class="center-me">
            <img v-if="scope.row.functionIcon" :src="scope.row.functionIcon" class="column-img" />
          </div>
        </template>
      </el-table-column>
      <el-table-column label="功能跳转地址" align="center" prop="functionPath" />
      <el-table-column label="功能类型" align="center" prop="functionType" :formatter="typeFormat" />
      <el-table-column label="显示顺序" align="center" prop="orderNum" />
      <el-table-column label="服务功能状态" align="center" prop="status">
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.status"
            active-value="0"
            inactive-value="1"
            @change="handleStatusChange(scope.row)"
          ></el-switch>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['ledger:function:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['ledger:function:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改查询功能管理对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="50%" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="功能名称" prop="functionName">
          <el-input v-model="form.functionName" placeholder="请输入服务功能名称" />
        </el-form-item>
        <el-form-item label="功能图标" prop="functionIcon">
          <el-upload
            class="avatar-uploader"
            :action="uploadImgUrl"
            :show-file-list="false"
            :headers="headers"
            :on-success="handleIconUploadSuccess"
            :before-upload="beforeUpload"
          >
            <img v-if="form.functionIcon" :src="form.functionIcon" class="map-pre" />
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
        <el-form-item label="功能跳转地址" prop="functionPath">
          <el-input v-model="form.functionPath" placeholder="请输入功能跳转地址" />
        </el-form-item>
        <el-form-item label="功能类型">
          <el-select
            v-model="form.functionType"
            placeholder="功能类型"
            clearable
            size="small"
            style="width: 240px"
          >
            <el-option
              v-for="dict in functionTypesOptions"
              :key="dict.dictValue"
              :label="dict.dictLabel"
              :value="dict.dictValue"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="显示顺序" prop="orderNum">
          <el-input-number v-model="form.orderNum" controls-position="right" :min="0" />
        </el-form-item>
        <el-form-item label="服务功能状态">
          <el-radio-group v-model="form.status">
            <el-radio
              v-for="dict in statusOptions"
              :key="dict.dictValue"
              :label="dict.dictValue"
            >{{dict.dictLabel}}</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<style>
.center-me {
  margin: 0 auto;
}
.el-upload-dragger {
  width: 180px;
  height: 120px;
}
.el-upload-dragger .el-icon-upload {
  margin: 14px 0 16px;
}
.el-upload-dragger .el-upload__text {
  font-size: 12px;
}
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.content {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  padding: 0px 20px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader {
  width: 128px;
  height: 128px;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 128px;
  height: 128px;
  line-height: 128px;
  text-align: center;
}
.column-img {
  width: 48px;
  height: 48px;
}
.avatar {
  width: 128px;
  height: 128px;
  display: block;
}
.map {
  width: 512px;
  height: 256px;
  display: block;
}
.map-pre {
  width: 128px;
  height: 128px;
  display: block;
}
.el-upload {
  display: block !important;
}
</style>
<script>
import {
  listFunction,
  getFunction,
  delFunction,
  addFunction,
  updateFunction,
  exportFunction,
  changeFunctionStatus,
} from "@/api/ledger/function";

import { getToken } from "@/utils/auth";

export default {
  name: "Function",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 状态数据字典
      statusOptions: [],
      functionTypesOptions: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 总条数
      total: 0,
      uploadImgUrl: process.env.VUE_APP_BASE_API + "/common/upload", // 上传的图片服务器地址
      headers: {
        Authorization: "Bearer " + getToken(),
      },
      // 查询功能管理表格数据
      functionList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        functionName: undefined,
        functionType: undefined,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        functionName: [
          { required: true, message: "服务功能名称不能为空", trigger: "blur" },
        ],
        functionIcon: [
          { required: true, message: "服务功能图标不能为空", trigger: "blur" },
        ],
      },
    };
  },
  created() {
    this.getDicts("sys_normal_disable").then((response) => {
      this.statusOptions = response.data;
    });
    this.getDicts("sys_ledger_function_type").then((response) => {
      this.functionTypesOptions = response.data;
    });
    this.getList();
  },
  methods: {
    beforeUpload(file) {
      if (file.type.indexOf("image/") == -1) {
        this.msgError("文件格式错误，请上传图片类型,如：JPG，PNG后缀的文件。");
      } else {
        const reader = new FileReader();
        reader.readAsDataURL(file);
      }
    },
    handleIconUploadSuccess(res, file) {
      this.form.functionIcon = res.url;
    },
    // 功能状态字典翻译
    typeFormat(row, column) {
      return this.selectDictLabel(this.functionTypesOptions, row.functionType);
    },
    // 功能状态修改
    handleStatusChange(row) {
      let text = row.status === "0" ? "启用" : "停用";
      this.$confirm(
        '确认要"' + text + '""' + row.functionName + '"该功能吗?',
        "警告",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      )
        .then(function () {
          return changeFunctionStatus(row.functionId, row.status);
        })
        .then(() => {
          this.msgSuccess(text + "成功");
        })
        .catch(function (e) {
          row.status = row.status === "0" ? "1" : "0";
          console.log(e)
        });
    },
    /** 查询查询功能管理列表 */
    getList() {
      this.loading = true;
      listFunction(this.queryParams).then((response) => {
        this.functionList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        functionId: undefined,
        functionName: undefined,
        functionIcon: undefined,
        functionPath: undefined,
        functionType: undefined,
        orderNum: 1,
        delFlag: undefined,
        status: "0",
        createBy: undefined,
        createTime: undefined,
        updateBy: undefined,
        updateTime: undefined,
        remark: undefined,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.functionId);
      this.single = selection.length != 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加查询功能管理";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const functionId = row.functionId || this.ids;
      getFunction(functionId).then((response) => {
        this.form = response.data;
        this.open = true;
        this.title = "修改查询功能管理";
      });
    },
    /** 提交按钮 */
    submitForm: function () {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.form.functionId != undefined) {
            updateFunction(this.form).then((response) => {
              if (response.code === 200) {
                this.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              }
            });
          } else {
            addFunction(this.form).then((response) => {
              if (response.code === 200) {
                this.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              }
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const functionIds = row.functionId || this.ids;
      this.$confirm(
        '是否确认删除查询功能管理编号为"' + functionIds + '"的数据项?',
        "警告",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      )
        .then(function () {
          return delFunction(functionIds);
        })
        .then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        })
        .catch(function () {});
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm("是否确认导出所有查询功能管理数据项?", "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(function () {
          return exportFunction(queryParams);
        })
        .then((response) => {
          this.download(response.msg);
        })
        .catch(function () {});
    },
  },
};
</script>